"use strict";
const BaseController = require("./base");

class WordFavoritesController extends BaseController {
  // 收藏单词
  async create() {
    const { ctx } = this;
    const { wordId } = ctx.request.body;
    const userId = ctx.state.user.user_id;

    // 检查是否已收藏
    const isFavorited = await ctx.service.wordFavorites.isFavorited(
      userId,
      wordId
    );
    if (isFavorited) {
      this.success('已收藏');
    } else {
      await ctx.service.wordFavorites.create(userId, wordId);
      this.success('收藏成功');
    }
  }

  // 取消收藏
  async destroy() {
    const { ctx } = this;
    const { wordId } = ctx.params;
    const userId = ctx.state.user.user_id;

    await ctx.service.wordFavorites.delete(userId, wordId);
    this.success();
  }

  // 获取用户收藏列表
  async index() {
    const { ctx } = this;
    const userId = ctx.state.user.user_id;
    const { page = 1, pageSize = 5 } = ctx.query;

    const result = await ctx.service.wordFavorites.getUserFavorites(
      userId,
      parseInt(page),
      parseInt(pageSize)
    );
    this.success(result);
  }

  // 检查是否收藏
  async check() {
    const { ctx } = this;
    const { wordId } = ctx.params;
    const userId = ctx.state.user.user_id;

    const isFavorited = await ctx.service.wordFavorites.isFavorited(
      userId,
      wordId
    );
    this.success(isFavorited);
  }
}

module.exports = WordFavoritesController;
